<template>
  <div>
    <Spin :spinning="this.loading" tip="Loading...">
      <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="100" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
    </Spin>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import * as validate from '@/utils/validate.js';
import { getOwnerInfoByOwnerNoAndDealerCode, getOwnerInfoByCertificate, getProvince, getCitys, getDistrict, getPostCode } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import pinyin from '@/components/Pinyin';
import moment from 'moment';
import { phoneCus, IDNumber, phoneAndSolidifyCus } from '@/utils/validate';
import { telePhone } from '@/utils/validate.js';
import { isFormEmpty, confirmAction, notifyAction, findFormItem } from '../../../../../utils';
import { menuUserAction } from '@/api/repair/repairReception/repairBusinessManger';
export default {
  name: 'addOwner_detailInfo',
  mixins: [dictionary],
  props: ['type', 'resData', 'gender'],
  data() {
    this.hiddenList = ['persoanalSpace', 'gender', 'birthday', 'ownerMarriage', 'dearName', 'dearMobile', 'dearHobby', 'dearPostion', 'chlidrenName'];
    this.allData = {};
    return {
      // jumpform: null,
      loading: false,
      formList: this.createFormList()
    };
  },
  mounted() {
    // this.jumpform = document.querySelector('.scroll-wrapper');
    this.getProvine();
    this.getResData();
  },
  methods: {
    resetAddress(val, itemList) {
      console.log(itemList);
      let newVal = itemList.find(item => item.value === val).text;
      console.log(newVal);
      let addressItem = this.formList.find(item => item.fieldName === 'address');
      let address = `${addressItem.initialValue || ''}`; // initialValue可能是undefined
      console.log(`resetAddress : ${address}`);
      addressItem.initialValue = `${address}${address.indexOf(String(newVal)) === -1 ? String(newVal) : ''}`;
    },
    createFormList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '基本信息'
        },
        {
          type: 'SELECT',
          label: '客户性质',
          fieldName: 'ownerProperty',
          itemList: this.createDictList(8011),
          initialValue: 80111001,
          disabled: this.type === 'add' ? false : true,
          rules: [{ required: true, message: '请选择客户性质', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'ownerNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '客户姓名',
          fieldName: 'ownerName',
          initialValue: '',
          maxlength: 30,
          disabled: this.type === 'add' ? false : true,
          rules: [{ required: true, message: '请输入客户姓名', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '性别',
          fieldName: 'gender',
          disabled: this.type === 'add' ? false : true,
          rules: [{ required: true, message: '请选择性别', trigger: 'change' }],
          itemList: this.createDictList(8012)
        },
        {
          type: 'INPUT',
          label: '座机',
          fieldName: 'phone',
          disabled: this.type === 'add' ? false : true
        },
        {
          type: 'INPUT',
          label: '客户手机',
          fieldName: 'mobile',
          rules: [
            { required: true, message: '请输入客户手机', trigger: 'blur' },
            {
              required: true,
              validator: (rule, value, callback) => {
                const message = '客户手机';
                phoneCus(rule, value, callback, message);
              },
              trigger: 'blur'
            }
          ],
          disabled: this.type === 'add' ? false : true
        },
        {
          type: 'SELECT',
          label: '证件类型',
          fieldName: 'ctCode',
          initialValue: 80131001,
          itemList: this.createDictList('8013'),
          rules: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
          change: val => {
            this.changeCtcode(val);
          },
          disabled: this.type === 'add' ? false : true
        },
        {
          type: 'INPUT',
          label: '证件号码',
          fieldName: 'certificateNo',
          style: { width: `calc(100% - 30px)` },
          descOptions: {
            isTooltip: true,
            content: '输入证件号码后会校验是否有重复客户档案，页面可能会重新加载，请耐心等待'
          },
          rules: [{ required: true, message: '请填写证件号码', trigger: 'blur' }],
          change: val => {
            const certificateNo = this.formList.find(x => x.fieldName === 'certificateNo');
            const ctCode = this.formList.find(item => item.fieldName === 'ctCode').initialValue;
            if (ctCode === 80131001) {
              certificateNo.rules = [{ required: true, validator: IDNumber, trigger: 'blur' }];
              /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(val) &&
                this.type == 'add' &&
                (this.formList.find(item => item.fieldName === 'birthday').initialValue = moment(val.slice(6, 10) + '-' + val.slice(10, 12) + '-' + val.slice(12, 14)));
            } else {
              certificateNo.rules = [{ required: true, message: '请输入证件号码', trigger: 'blur' }];
            }
            if (ctCode && val) {
              this.checkRepeatOwner(ctCode, val);
            }
          },
          disabled: this.type === 'add' ? false : true
        },
        {
          type: 'INPUT',
          label: '传真',
          fieldName: 'fax'
        },
        {
          type: 'INPUT',
          label: 'E-Mail',
          fieldName: 'email',
          rules: [{ validator: validate.EmailValidate, trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '所在省份',
          fieldName: 'province',
          itemList: [],
          disabled: this.type === 'add' ? false : true,
          change: val => {
            this.provinceChange(val);
            let itemList = this.formList.find(item => item.fieldName === 'province').itemList;
            // this.resetAddress(val || '', itemList);
          },
          rules: [{ required: true, message: '请选择所在省份', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '城市',
          fieldName: 'city',
          itemList: [],
          disabled: this.type === 'add' ? false : true,
          change: val => {
            this.cityChange(val);
            let itemList = this.formList.find(item => item.fieldName === 'city').itemList;
            // this.resetAddress(val || '', itemList);
          },
          rules: [{ required: true, message: '请选择城市', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '区县',
          fieldName: 'district',
          itemList: [],
          disabled: this.type === 'add' ? false : true,
          change: val => {
            this.districtChange(val);
            let itemList = this.formList.find(item => item.fieldName === 'district').itemList;
            // this.resetAddress(val || '', itemList);
          },
          rules: [{ required: true, message: '请选择区县', trigger: 'change' }]
        },

        {
          type: 'INPUT',
          label: '邮编',
          fieldName: 'zipCode',
          rules: [{ validator: validate.zipCode, trigger: 'blur' }]
        },
        {
          type: 'TEXT_AREA',
          label: '居住地址',
          fieldName: 'address',
          placeholder: '请输入...',
          selfCols: 3, // 元素占据几行
          rows: 2,
          disabled: this.type === 'add' ? false : true,
          rules: [{ required: true, message: '请输入地址', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '单位性质',
          fieldName: 'industryFirst',
          itemList: this.createDictList('8251')
          // rules: [{ required: true, message: '请选择单位性质', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '行业类型',
          fieldName: 'industrySecond',
          itemList: this.createDictList('8252')
          // rules: [{ required: true, message: '请选择行业类型', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '职业',
          fieldName: 'vocationType',
          itemList: this.createDictList(8022)
          // rules: [{ required: true, message: '请选择行业类型', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '职称',
          fieldName: 'position',
          itemList: this.createDictList(8023)
          // rules: [{ required: true, message: '请选择行业类型', trigger: 'change' }]
        },
        {
          type: 'DATE',
          label: '生日',
          fieldName: 'birthday',
          format: 'yyyy-MM-dd'
        },
        {
          type: 'SELECT',
          label: '婚姻状况',
          fieldName: 'ownerMarriage',
          itemList: this.createDictList('8018')
        },
        {
          type: 'SELECT',
          label: '喜欢联系方式',
          fieldName: 'bestConcatType',
          itemList: this.createDictList('9123')
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '爱好',
          fieldName: 'hobby',
          initialValue: [],
          itemList: this.createDictList('8020')
        },
        {
          type: 'SELECT',
          label: '子女状况',
          fieldName: 'isChlidren',
          itemList: this.createDictList(1004)
        },
        {
          type: 'SELECT',
          label: '年家庭收入',
          fieldName: 'familyIncome',
          itemList: this.createDictList(1290)
        }
      ];
    },
    // 根据身份证号查询该经销商是否有相同的车主
    async checkRepeatOwner(ctCode, certificateNo) {
      this.loading = true;
      const res = await getOwnerInfoByCertificate({ ctCode: ctCode, certificateNo: certificateNo });
      if (res.data.ownerNo) {
        try {
          // await confirmAction('查询到已存在客户，是否带回客户信息');
          // 直接将数据带回
          await this.assignment(res);
          // let auth = await menuUserAction();
          // if (!auth.data || !auth.data.find(x => x.actionUrl === '111111')) {
          //   this.formList.forEach(x => {
          //     x.disabled = true;
          //   });
          //
          // }
          this.formList = [...this.formList];
          this.formList.forEach(x => {
            if (x.fieldName === 'ownerProperty') {
              x.disabled = true;
            }
            if (x.fieldName === 'ownerName') {
              x.disabled = true;
            }
            if (x.fieldName === 'phone') {
              x.disabled = true;
            }
            if (x.fieldName === 'mobile') {
              x.disabled = true;
            }
            if (x.fieldName === 'ctCode') {
              x.disabled = true;
            }
            if (x.fieldName === 'certificateNo') {
              x.disabled = true;
            }
            if (x.fieldName === 'province') {
              x.disabled = true;
            }
            if (x.fieldName === 'city') {
              x.disabled = true;
            }
            if (x.fieldName === 'district') {
              x.disabled = true;
            }
            if (x.fieldName === 'address') {
              x.disabled = true;
            }
            if (x.fieldName === 'gender') {
              x.disabled = true;
            }
          });
          findFormItem(this.formList, 'ownerProperty').disabled = true;
          this.fetchParams = { ...this.fetchParams };
          // this.formList.forEach(x => {
          //   x.disabled = true;
          // });
        } catch (err) {
          this.loading = false;
          return;
        }
      }
      this.loading = false;
    },
    formChangeHandle(val) {
      this.allData = val;
    },
    async getData() {
      let dataObj = {};
      this.formList.forEach(item => {
        dataObj[item.fieldName] = item.initialValue;
      });
      return dataObj;
    },
    async getDataSave() {
      let [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      return data;
    },
    async getResData() {
      if (this.type != 'add') {
        // this.loading = true;
        if (isFormEmpty(this.resData.ownerNo)) {
          return notifyAction('车主编号不能为空！', 'warning');
        }
        let parm = {
          ownerNoDetail: this.resData.ownerNo,
          ownerCode: this.resData.OWNER_CODE
        };
        this.loading = true;
        const res = await getOwnerInfoByOwnerNoAndDealerCode(parm);
        await this.assignment(res);
        // this.formList.find(item => item.fieldName === 'ownerName').disabled = this.type === 'edit' ? false : true;
        // if (res.data.ownerProperty !== 80111001) {
        //   this.formList.forEach(x => {
        //     if (this.hiddenList.includes(x.fieldName)) {
        //       x.hidden = true;
        //       if (x.fieldName === 'gender') {
        //         x.rules = [];
        //       }
        //     }
        //   });
        // }
        this.loading = false;
      }
    },
    async assignment(res) {
      const numberTrans = [
        'concatTime',
        'industry',
        'companyNumber',
        'registerCapital',
        'customerEvalua',
        'carStatus',
        'typeEchange',
        'dearHobby',
        'repairLargeCustomer',
        'saleLargeCustomer',
        'gender'
      ];
      // if (this.type != 'add') {
      if (res.resultCode === 200) {
        if (res.data.province) {
          const res_getCitys = await getCitys(res.data.province);
          this.formList.find(item => item.fieldName === 'city').itemList = res_getCitys.data.map(x => ({ value: x.regionId, text: x.regionName }));
        }
        if (res.data.city) {
          const res_getDistrict = await getDistrict(res.data.city);
          this.formList.find(item => item.fieldName === 'district').itemList = res_getDistrict.data.map(x => ({ value: x.regionId, text: x.regionName }));
        }
        this.formList.forEach(x => {
          const val = res.data[x.fieldName];
          if (x.fieldName == 'ownerName') {
            // this.changeOwnerName(val);
            x.initialValue = val;
          } else if (x.fieldName === 'hobby' && val) {
            if (res.data.hobby != null) {
              let hobby = res.data.hobby.split(',');
              hobby = hobby.map(Number);
              x.initialValue = hobby;
            } else {
              x.initialValue = [];
            }
          } else if (x.fieldName === 'prePay' || x.fieldName === 'arrearageAmount') {
            x.initialValue = val ? val : 0;
          } else if (x.fieldName === 'financialType' || x.fieldName === 'dearPostion') {
            x.initialValue = val ? val : undefined;
          } else if (numberTrans.includes(x.fieldName) && val) {
            x.initialValue = Number(val);
          } else {
            x.initialValue = val;
          }
        });
      }
      // }
    },
    async getProvine() {
      const res = await getProvince();
      this.formList.find(item => item.fieldName === 'province').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
    },
    changeCtcode(id) {
      console.log('id', id);
      if (id == 80131001) {
        this.formList.find(item => item.fieldName === 'certificateNo').initialValue = '';
        this.formList.find(item => item.fieldName === 'certificateNo').rules = [
          { required: true, message: '请输入证件号', trigger: 'blur' },
          { validator: validate.IDNumber, trigger: 'blur' }
        ];
        this.formList = [...this.formList];
      } else {
        this.formList.find(item => item.fieldName === 'certificateNo').rules = [{ required: true, message: '请输入证件号', trigger: 'blur' }];
        this.formList.find(item => item.fieldName === 'certificateNo').initialValue = '';
        this.formList = [...this.formList];
      }
    },
    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    async provinceChange(regionId) {
      this.clearFormItem(this.formList.find(item => item.fieldName === 'city'));
      this.clearFormItem(this.formList.find(item => item.fieldName === 'district'));
      if (!regionId) return;
      const res = await getCitys(regionId);
      this.formList.find(item => item.fieldName === 'city').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
    },
    async cityChange(regionId) {
      this.clearFormItem(this.formList.find(item => item.fieldName === 'district'));
      if (!regionId) return;
      const res = await getDistrict(regionId);
      this.formList.find(item => item.fieldName === 'district').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
      let ress = await getPostCode({ regionId: regionId }); // 获取邮编
      this.$nextTick(() => {
        this.formList.find(item => item.fieldName === 'zipCode').initialValue = ress.data.POST_CODE;
      });
    },
    async districtChange(regionId) {
      let ress = await getPostCode({ regionId: regionId }); // 获取邮编
      this.$nextTick(() => {
        this.formList.find(item => item.fieldName === 'zipCode').initialValue = ress.data.POST_CODE;
      });
    }
  }
};
</script>

<style scoped>
.btnWrap {
  display: flex;
  justify-content: center;
}
</style>
